package com.yunzai.file.controller;

import com.yunzai.file.service.IFileDownloadService;
import com.yunzai.file.service.IFileUploadService;
import com.yunzai.generic.domain.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class FileUploadController {

    @Autowired
    private IFileUploadService uploadService;

    @Autowired
    private IFileDownloadService uploadDownloadService;

    @PostMapping("/upload")
    public JSONResult handleUpload(@RequestParam("file") MultipartFile file) {
        String filename = uploadService.uploadFile(file);
        return JSONResult.success("上传成功", "/download/" + filename);
    }

    @GetMapping("/download/{filename}")
    public ResponseEntity<Resource> downloadFile(@PathVariable("filename") String filename) {
        try {
            Resource resource = uploadDownloadService.downloadFile(filename);
            // 4. 设置安全响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment; filename=\"" + resource.getFilename() + "\"");
            headers.add(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate");
            headers.add(HttpHeaders.PRAGMA, "no-cache");
            headers.add(HttpHeaders.EXPIRES, "0");

            // 5. 返回文件流
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(resource.contentLength())
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);

        } catch (IllegalArgumentException e) {
            // 处理非法路径请求
            return ResponseEntity.badRequest().body(null);
        } catch (Exception e) {
            // 处理其他异常情况
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/avatar/{filename}")
    public ResponseEntity<Resource> avatar(@PathVariable("filename") String filename) {
        try {
            Resource resource = uploadDownloadService.avatar(filename);
            // 5. 返回文件流
            return ResponseEntity.ok()
                    .contentLength(resource.contentLength())
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);

        } catch (IllegalArgumentException e) {
            // 处理非法路径请求
            return ResponseEntity.badRequest().body(null);
        } catch (Exception e) {
            // 处理其他异常情况
            return ResponseEntity.notFound().build();
        }
    }

}
